package com.tmxk.employee.servlet;

import com.alibaba.fastjson.JSONObject;
import com.tmxk.employee.pojo.entity.TTripMode;
import com.tmxk.employee.service.TTripModeService;
import com.tmxk.employee.service.impl.TTripModeServiceImpl;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 出行方式控制层( 和前端(view视图层进行交互) )
 * Servlet在多线程场景下,是非安全的,因此不建议在Servlet应用中定义成员变量
 */
@WebServlet(name = "TTripModeServlet",urlPatterns = "/TTripModeServlet")
public class TTripModeServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(TTripModeServlet.class);
    String name;  //不建议定义成员变量,如项目需求,一定要定义,建议加同步
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置request、response字符编码格式,解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //创建业务访问层对象
        TTripModeService tTripModeService = new TTripModeServiceImpl();
        //调用查询所有出行方式方法
        List<TTripMode> tTripModes = tTripModeService.queryAllMode(null);
      //  System.out.println(tTripModes);  // 在企业中，不建议加sout控制台输出语句
        logger.info("tTripModes>:" + tTripModes);
        // 将 tTripModes 集合数据转换成json数据格式
        // 提供了fastjson jar包快速转换, fastjson 低版本存在安全漏洞
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tTripModes" , tTripModes);
        logger.info("tTripModes转换成json格式数据:" + jsonObject);
        // 通过response将后端数据响应给前端
        PrintWriter out = response.getWriter();
        out.println(jsonObject);
    }
}
